/**
 * @file tellwait1.c
 * @author liangwenhao (1943080020@qq.com)
 * @brief 
 * @version 0.1
 * @date 2021-07-26
 * 
 * @copyright Copyright (c) 2021
 * 
 * @authorGitee  https://gitee.com/liangwenhao
 * @authorGithub https://github.com/WHaoL
 * @authorBlogs https://blog.csdn.net/liangwenhao1108
 *  
 * @Code Description: P198 对于带有竞争条件的程序，测试父子进程调用顺序
 *                    使用了TELL和WAIT函数
 *  
 */

#include "apue.h"
static void charatatime(char *str);

#define Parent_First 1 //父进程先执行
// #define Child_First 1 //子进程先执行

int main(void)
{
    pid_t pid;

    TELL_WAIT(); //apue通过信号设计出来的，目前先不用管

    if ((pid = fork()) < 0)
    {
        err_sys("fork error");
    }
    
#ifdef Parent_First
    else if (pid == 0)
    {
        WAIT_PARENT(); // parent goes first 等待父进程先执行完毕
        charatatime("output from child\n");
    }
    else
    {
        charatatime("output from parent\n");
        TELL_CHILD(pid); //通知child 当前进程执行完毕
    }

#elif Child_First
    else if (pid == 0)
    {
        charatatime("output from child\n");
        TELL_PARENT(getppid()); //通知父进程 当前进程执行完毕
    }
    else
    {
        WAIT_CHILD(); // 等待子进程先执行完毕
        charatatime("output from parent\n");
    }
#endif


    exit(0);
}

static void charatatime(char *str)
{
    char *ptr;
    int c;
    setbuf(stdout, NULL); // set unbuffered
    for (ptr = str; (c = *ptr++) != 0;)
        putc(c, stdout);
}